package com.itheima.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.R;
import com.itheima.api.*;
import com.itheima.dto.PmsProductParam;
import com.itheima.dto.PmsProductResult;
import com.itheima.dto.PmsPruductQueryParam;
import com.itheima.pojo.db.PmsProduct;
import com.itheima.pojo.db.PmsProductVertifyRecord;
import com.itheima.pojo.db.PmsSkuStock;
import com.itheima.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author chensen
 * @create 2022/10/14/18:59
 */
@Service
public class PmsProductService {

    @DubboReference
    private PmsSkuStockApi pmsSkuStockApi;
    @DubboReference
    private PmsProductLadderApi pmsProductLadderApi;
    @DubboReference
    private PmsProductApi pmsProductApi;
    @DubboReference
    private PmsProductFullReductionApi pmsProductFullReductionApi;
    @DubboReference
    private PmsProductAttributeValueApi pmsProductAttributeValueApi;
    @DubboReference
    private PmsMemberPriceApi pmsMemberPriceApi;
    @DubboReference
    private CmsSubjectProductRelationApi cmsSubjectProductRelationApi;
    @DubboReference
    private CmsPrefrenceAreaProductRelationApi cmsPrefrenceAreaProductRelationApi;
    @DubboReference
    private PmsProductVertifyRecordApi pmsProductVertifyRecordApi;
    @DubboReference
    private PmsProductCategoryApi pmsProductCategoryApi;
    public R create(PmsProductParam productParam) {
        PmsProduct product = productParam;
        product.setId(null);
        pmsProductApi.insert(product);
        Long productId = product.getId();
        this.insertList(pmsMemberPriceApi, productParam.getMemberPriceList(), productId);
        this.insertList(pmsProductLadderApi, productParam.getProductLadderList(), productId);
        this.insertList(pmsProductFullReductionApi, productParam.getProductFullReductionList(), productId);
        this.handleSkuStockCode(productParam.getSkuStockList(), productId);
        this.insertList(pmsSkuStockApi, productParam.getSkuStockList(), productId);
        this.insertList(pmsProductAttributeValueApi, productParam.getProductAttributeValueList(), productId);
        this.insertList(cmsSubjectProductRelationApi, productParam.getSubjectProductRelationList(), productId);
        this.insertList(cmsPrefrenceAreaProductRelationApi, productParam.getPrefrenceAreaProductRelationList(), productId);
        return R.success("添加成功");
    }

    private void handleSkuStockCode(List<PmsSkuStock> skuStockList, Long productId) {
        if (CollectionUtils.isEmpty(skuStockList)) return;
        for (int i = 0; i < skuStockList.size(); i++) {
            PmsSkuStock skuStock = skuStockList.get(i);
            if (StringUtils.isEmpty(skuStock.getSkuCode())) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                StringBuilder sb = new StringBuilder();
                //日期
                sb.append(sdf.format(new Date()));
                //四位商品id
                sb.append(String.format("%04d", productId));
                //三位索引id
                sb.append(String.format("%03d", i + 1));
                skuStock.setSkuCode(sb.toString());
            }
        }
    }

    private void insertList(Object api, List dataList, Long projectId) {
        try {
            if (ObjectUtil.isEmpty(dataList)) return;
            Method insertList = api.getClass().getMethod("insertList", List.class, Long.class);
            insertList.invoke(api, dataList, projectId);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public R listByCondition(PmsPruductQueryParam productQueryParam, Integer pageNum, Integer pageSize) {
        IPage<PmsProduct> page = new Page<>(pageNum, pageSize);
        IPage<PmsProduct> pageL = pmsProductApi.listByCondition(page, productQueryParam);
        return R.success(PageResult.init(pageL));
    }

    public R list(String keyword) {
        List<PmsProduct> list = pmsProductApi.list(keyword);
        return R.success(list);
    }

    public R updateDeleteStatus(List<Long> ids, Integer deleteStatus) {
        int count = pmsProductApi.updateDeleteStatus(ids, deleteStatus);
        if (count > 0) {
            return R.success("修改成功!");
        }
        return R.error("商品正在上架中,请取消上架后再试");
    }

    public R updateNewStatus(List<Long> ids, Integer newStatus) {
        int count = pmsProductApi.updateNewStatus(ids, newStatus);
        if (count > 0) {
            return R.success("修改成功!");
        }
        return R.error("修改失败！");
    }

    public R updatePublishStatus(List<Long> ids, Integer publishStatus) {
        int count = pmsProductApi.updatePublishStatus(ids, publishStatus);
        if (count > 0) {
            return R.success("修改成功!");
        }
        return R.error("修改失败！");
    }

    public R updateRecommendStatus(List<Long> ids, Integer recommendStatus) {
        int count = pmsProductApi.updateRecommendStatus(ids, recommendStatus);
        if (count > 0) {
            return R.success("修改成功!");
        }
        return R.error("修改失败！");
    }

    public R updateVerifyStatus(List<Long> ids, Integer verifyStatus, String detail) {
        int count = pmsProductApi.updateVerifyStatus(ids, verifyStatus);
        List<PmsProductVertifyRecord> list = new ArrayList<>();
        for (Long id : ids) {
            PmsProductVertifyRecord record = new PmsProductVertifyRecord();
            record.setProductId(id);
            record.setCreateTime(new Date());
            record.setDetail(detail);
            record.setStatus(verifyStatus);
            record.setVertifyMan("test");
            list.add(record);
        }
        pmsProductVertifyRecordApi.insertList(list);
        if (count > 0) {
            return R.success("修改成功!");
        }
        return R.error("修改失败！");
    }

    public R update(Long id, PmsProductParam productParam) {
        int count;

        PmsProduct product = productParam;
        product.setId(id);
        pmsProductApi.updateById(product);

        pmsMemberPriceApi.deleteById(id);
        this.insertList(pmsMemberPriceApi, productParam.getMemberPriceList(), id);

        pmsProductLadderApi.deleteById(id);
        this.insertList(pmsProductLadderApi, productParam.getProductLadderList(), id);

        pmsProductFullReductionApi.deleteById(id);
        this.insertList(pmsProductFullReductionApi, productParam.getProductFullReductionList(), id);

        pmsSkuStockApi.delete(id);
        handleSkuStockCode(productParam.getSkuStockList(), id);
        this.insertList(pmsSkuStockApi, productParam.getSkuStockList(), id);

        pmsProductAttributeValueApi.deleteById(id);
        this.insertList(pmsProductAttributeValueApi, productParam.getProductAttributeValueList(), id);

        cmsSubjectProductRelationApi.deleteById(id);
        this.insertList(cmsSubjectProductRelationApi, productParam.getSubjectProductRelationList(), id);

        cmsPrefrenceAreaProductRelationApi.deleteById(id);
        this.insertList(cmsPrefrenceAreaProductRelationApi, productParam.getPrefrenceAreaProductRelationList(), id);

        count = 1;
        if (count > 0) {
            return R.success("修改成功");
        }
        return R.error("修改失败！");
    }


    public R updateInfo(Long id) {
        PmsProduct product = pmsProductApi.getUpdateInfo(id);
        PmsProductResult result =new PmsProductResult();
        BeanUtils.copyProperties(product, result);
        result.setCateParentId(pmsProductCategoryApi.getCatePid(product));
        result.setMemberPriceList(pmsMemberPriceApi.selectByPId(id));
        result.setPrefrenceAreaProductRelationList(cmsPrefrenceAreaProductRelationApi.selectByPid(id));
        result.setProductAttributeValueList(pmsProductAttributeValueApi.selectByPid(id));
        result.setProductFullReductionList(pmsProductFullReductionApi.selectByPid(id));
        result.setProductLadderList(pmsProductLadderApi.selectByPid(id));
        result.setSkuStockList(pmsSkuStockApi.selectByPid(id));
        result.setSubjectProductRelationList(cmsSubjectProductRelationApi.selectById(id));

        return R.success(result);
    }
}
